#! /usr/bin/perl -w

use threads;
use threads::shared;
use strict;

use constant  MAX => 30;

my @hosts = map{ "192.168.1." . $_ } 1..254;
my $host_cnt = @hosts;
my %status : shared; 
my $thread_num : shared = 0;

foreach my $host (@hosts) {
    select(undef, undef, undef, 0.2) while $thread_num >= MAX;
    lock $thread_num;
    $thread_num++;
    
    my $t = threads->new(\&do_ping, $host);
    $t->detach;

    print "thread new: $t\n";
    print "thread cnt: $thread_num\n";
    print "host: $host\n";
}

select(undef, undef, undef, 0.2) while ($thread_num != 0);

foreach my $t (sort {$status{$b} cmp $status{$a}} keys %status) {
    print "$t => $status{ $t }\n";
}

sub do_ping($) {
    my $host = shift;
    my $t;
    $t = !system( "ping -q -c1 -t1 $host > /dev/null" ) ? "alive" : "down";
    {
        lock %status;
        $status{ $host } = $t;
    }

    lock $thread_num;
    $thread_num--;
}
